package com.itheima.userdemo.controller;

import com.itheima.userdemo.pojo.User;
import com.itheima.userdemo.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/regServlet")
public class RegisterServlet extends HttpServlet {
    // doGet doPost?

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("doPost...");
        // 1. 接收用户名和密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        System.out.println(username+" "+password);
        // 2. 调用Service查询用户
        UserService userService = new UserService();
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        // 如果验证码不对， 是否还继续来？
        // 获取注册时，提交的验证码
        String userSubmitChkCode = req.getParameter("checkCode");
        System.out.println("提交的验证码:"+userSubmitChkCode);
        // 与之前生成的验证码进行比对
        // 验证码是在哪里生成的？另外，我们如何读取到之前生成的验证码
        // 读取session中存储的验证码
        HttpSession httpSession = req.getSession();
        String trueCheckCode = (String)httpSession.getAttribute("checkCode");
        System.out.println("真正的验证码(从session获取的)"+trueCheckCode);
        if(!trueCheckCode.equals(userSubmitChkCode)){
            // 验证码不正确，不能继续往后了
            req.setAttribute("errMessage","验证码不正确");
            req.getRequestDispatcher("/register.jsp").forward(req,resp);
            return;
        }
        // 注册用户
        boolean isOk = userService.register(user);
        // 3. 判断用户
        if(isOk){
            // 注册成功
            // 跳转到登录页
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
        }else{
           // 注册失败，请求转发
            req.setAttribute("errMessage","用户名已存在");
            req.getRequestDispatcher("/register.jsp").forward(req,resp);
        }
    }
}
